package org.common.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.common.constant.StaticConstant;
import org.common.exception.DtsException;
import org.common.service.EmailService;
import org.common.service.RedisService;
import org.common.type.CaptchaCodeType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private RedisService redisService;

    @Resource
    JavaMailSender mailSender;

    private static long expireTime = 300;


    @Override
    public void sendEmail(String to, String subject, String text) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        mailSender.send(helper.getMimeMessage());
    }

    @Override
    public void sendCaptchaCode(String to, CaptchaCodeType type) {
        Random random = new Random();
        StringBuilder captchaCodeStr = new StringBuilder();
        redisService.execute(() -> {
            String existCode = redisService.get(type + "-" + to);
            if (StringUtils.isNotBlank(existCode)) {
                throw new DtsException(201, "201", "已发送验证码，请勿重复操作");
            }
            for (int i = 0; i < 6; i++) {
                int randomNumber = random.nextInt(10);
                captchaCodeStr.append(randomNumber);
            }
            redisService.setWithExpire(CaptchaCodeType.REG + "-" + to, captchaCodeStr.toString(), expireTime);
        });
        String content = String.format("%s\n验证码有效时间为%d分钟", captchaCodeStr, expireTime / 60);
        this.sendEmail(to, StaticConstant.SYSTEM_NAME, content);
    }

    public static void main(String[] args) {
        System.out.println(CaptchaCodeType.RETRIEVE_PASSWORD);
    }
}
